using System;
using UnityEngine;
using DG.Tweening;

public class SlidePopupWithOffset : MonoBehaviour
{
    [Header("弹窗设置")]
    public RectTransform popupPanel; // 弹窗的 RectTransform
    public float animationDuration = 0.5f; // 动画持续时间

    [Header("背景设置")]
    public CanvasGroup background; // 背景 CanvasGroup
    public float maxBackgroundAlpha = 0.5f; // 背景最大透明度

    [Header("位置偏移设置")]
    public Vector2 offset; // 弹窗滑入时的偏移值

    private Vector2 hiddenPosition; // 弹窗隐藏时的位置
    private Vector2 visiblePosition; // 弹窗显示时的位置

    public float StayTime;
    private float StayTimer;

    private void Start()
    {
        // 计算初始位置
        hiddenPosition = popupPanel.anchoredPosition; // 隐藏位置为当前初始位置
        visiblePosition = hiddenPosition + offset; // 显示位置为隐藏位置加上偏移量

        // 初始化弹窗和背景
        popupPanel.anchoredPosition = hiddenPosition; // 设置为隐藏位置
        background.alpha = 0f; // 背景初始透明
    }

    public void Update()
    {
        if (StayTimer <= 0)
        {
            HidePopup();
        }
        else
        {
            StayTimer -= Time.deltaTime;
        }

    }

    /// <summary>
    /// 显示弹窗并渐变背景。
    /// </summary>
    public void ShowPopup()
    {
        background.gameObject.SetActive(true); // 确保背景可见

        // 渐变背景透明度
        background.DOFade(maxBackgroundAlpha, animationDuration).SetEase(Ease.Linear);

        // 弹窗滑入
        popupPanel.gameObject.SetActive(true);
        popupPanel.DOAnchorPos(visiblePosition, animationDuration).SetEase(Ease.OutCubic);
        StayTimer = StayTime;
    }

    /// <summary>
    /// 隐藏弹窗并渐隐背景。
    /// </summary>
    public void HidePopup()
    {
        // 渐隐背景透明度
        background.DOFade(0f, animationDuration).SetEase(Ease.Linear);

        // 弹窗滑出
        popupPanel.DOAnchorPos(hiddenPosition, animationDuration)
            .SetEase(Ease.InCubic);
    }
}